Registry.require(["helper", "convert"],
function() {
    var q = Registry.get("helper"),
    r = Registry.get("convert"),
    t,
    B = function(a) {
        return a && "http" == a.substr(0, 4)
    },
    E = "internal user-agent accept-charset accept-encoding access-control-request-headers access-control-request-method connection content-length cookie cookie2 date dnt expect host keep-alive origin referer te trailer transfer-encoding upgrade via".split(" "),
    C = function(a) {
        return - 1 != E.indexOf(a) || 0 === a.indexOf("proxy-") || 0 === a.indexOf("sec-")
    },
    F = {
        "cache-control": "no-cache",
        pragma: "no-cache"
    },
    G = {
        "cache-control": "max-age=0, must-revalidate"
    },
    v = function(a) {
        return {
            responseXML: "",
            responseText: "",
            response: null,
            readyState: 4,
            responseHeaders: "",
            status: 0,
            statusText: "",
            error: a || "Forbidden"
        }
    },
    x = function(a) {
        if ("Blob" === a.type) return new Blob([r.str2arrbuf(a.value)]);
        if ("File" === a.type) return new File([r.str2arrbuf(a.value)], a.name, {
            type: a.meta,
            lastModified: a.lastModified || Date.now()
        });
        if ("FormData" == a.type) {
            var d = new FormData;
            Object.keys(a.value).forEach(function(b) {
                var c = "Array" === a.value[b].type,
                g = x(a.value[b]),
                m = c ? g: [g];
                m.forEach(function(a, c) {
                    d.append(b, m[c])
                })
            });
            return d
        }
        if ("Array" === a.type || "Object" === a.type) {
            var g, c, h;
            "Object" === a ? (h = Object.keys(a.value), c = function(a) {
                return a < h.length ? h[a] : null
            },
            g = {}) : (c = function(b) {
                return b < a.value.length ? b: null
            },
            g = []);
            for (var k, n = 0; null !== (k = c(n)); n++) g[k] = x(a.value[k]);
            return g
        }
        return a.value
    },
    w = function(a) {
        var d = {};
        a && a.split("\n").forEach(function(a) { (a = a.match(/^([^:]+): ?(.*)/)) && (d[a[1].toLowerCase()] = a[2] || "")
        });
        return d
    },
    H = function(a, d, g) {
        void 0 === g && (g = {});
        var c = q.assign({},
        d || {}),
        h = function(a, b) {
            if (c[a]) c[a]("function" == typeof b ? b() : b)
        };
        d = function(a, b) {
            c[a] && (h(a, b), c[a] = null)
        };
        if (g.internal || B(a.url)) {
            var k = window.fetch && a.url && "http" == a.url.substr(0, 4),
            n = !t.mozAnon && a.anonymous,
            b = a.fetch;
            return k && (n || b) ? y(a, c, g, d, h) : z(a, c, g, d, h)
        }
        console.warn("xhr: invalid scheme of url:", a.url);
        a = v("Invalid scheme");
        d("onerror", a);
        d("ondone", a)
    },
    A = "tm-finalurl" + rea.runtime.short_id.toLowerCase(),
    D = "tm-setcookie" + rea.runtime.short_id.toLowerCase(),
    y = function(a, d, g, c, h) {
        var k = function(a) {
            var b = [],
            c,
            l;
            a.headers && (c = a.headers.get(A) || a.url, a.headers.forEach(function(a, l) {
                var c = l.toLowerCase(); - 1 == [A, D].indexOf(c) && b.push(c + ":" + a)
            }), (l = a.headers.get(D)) && b.push("set-cookie:" + l));
            return {
                readyState: 4,
                responseHeaders: b.join("\n"),
                finalUrl: c,
                status: a.status,
                statusText: a.statusText
            }
        },
        n = function(b) { (function(a, b) {
                for (var l = [], e = 0, c = a.length; e < c; e += b) l.push(a.slice(e, b + e));
                return l
            })(b, parseInt(a.partialSize)).forEach(function(a) {
                h("onpartial", {
                    partial: a
                })
            })
        };
        try {
            var b = {};
            b.method = a.method || "GET";
            b.redirect = "follow";
            if (a.nocache || a.revalidate) b.cache = "no-store";
            b.credentials = a.anonymous ? "omit": "include";
            if (a.headers) {
                var p = {};
                Object.keys(a.headers).forEach(function(b) {
                    var c = b,
                    d = a.headers[b];
                    if (t.prefix) C(b.toLowerCase()) && (c = t.prefix + b, d = null === d ? "": r.encodeS(d));
                    else if (null === d) return;
                    p[c] = d
                });
                b.headers = new window.Headers(p)
            }
            void 0 !== a.timeout && (b.timeout = a.timeout);
            void 0 !== a.data && (b.body = "typified" === a.data_type ? x(a.data) : "string" === typeof a.data ? a.data: JSON.stringify(a.data));
            var q = window.fetch(a.url, b).then(function(b) {
                var f = k(b); (0 !== f.status || 200 > f.status || 300 <= f.status) && 0 < a.retries ? (a.retries--, y(a, d, g, c, h)) : function() {
                    var c;
                    if (b.ok) void 0 !== a.responseType ?
                    function() {
                        var l, e = a.responseType ? a.responseType.toLowerCase() : "";
                        if (a.convertBinary) {
                            if ("document" == e) return l = w(f.responseHeaders)["content-type"] || "text/html",
                            new window.Promise(function(a) {
                                return b.text().then(function(b) {
                                    a({
                                        document: b,
                                        contentType: l
                                    })
                                })
                            });
                            if ("json" == e) return b.text();
                            if ("arraybuffer" == e || "blob" == e) return b.arrayBuffer().then(function(a) {
                                return r.arrbuf2str(a)
                            })
                        } else {
                            if ("arraybuffer" == a.responseType) return b.arrayBuffer();
                            if ("blob" == a.responseType) return b.blob();
                            if ("document" == a.responseType) return l = w(f.responseHeaders)["content-type"] || "text/xml",
                            (new window.DOMParser).parseFromString(b.text(), l);
                            if ("json" == a.responseType) return JSON.parse(b.text());
                            console.warn("xhr: responseType", a.responseType, " is not implemented!");
                            return b.text()
                        }
                    } ().then(function(a) {
                        f.response = a;
                        c()
                    }) : b.text().then(function(a) {
                        f.response = a;
                        c()
                    });
                    else return f.responseXML = null,
                    f.responseText = "",
                    f.response = null,
                    {
                        done: function(a) {
                            a()
                        }
                    };
                    return {
                        done: function(a) {
                            c = a
                        }
                    }
                } ().done(function() {
                    if (a.partialSize && d.onpartial) {
                        var b = a.convertBinary && f.response ? f.response: f.responseText; ["response", "responseText", "responseXML"].forEach(function(a) {
                            delete f[a]
                        });
                        b && (b.length > a.partialSize ? n(b) : f.response_data = b)
                    }
                    c("onload", f);
                    c("ondone", f)
                })
            }).
            catch(function(a) {
                a = k({
                    status: 408,
                    statusText: a.message || "Request Timeout"
                });
                c("onerror", a);
                c("ondone", a)
            })
        } catch(m) {
            console.error(m.stack),
            b = v(m.message),
            c("onerror", b),
            c("ondone", b)
        }
        return {
            abort: function() {
                try {
                    q.abort && q.abort()
                } catch(a) {}
            }
        }
    },
    z = function(a, d, g, c, h) {
        var k, n, b = new XMLHttpRequest(a.anonymous ? {
            mozAnon: !0
        }: {}),
        p = function(l) {
            var e = "",
            c = a.url;
            if (2 <= b.readyState) {
                if (e = b.getAllResponseHeaders()) e = e.replace(/tm-finalurl[0-9a-zA-Z]*\: .*[\r\n]{1,2}/i, ""),
                e = e.replace(/tm-setcookie[0-9a-zA-Z]*\:/i, "set-cookie:");
                var d;
                if (d = b.getResponseHeader(A) || b.responseURL) c = d
            }
            e = {
                readyState: b.readyState,
                responseHeaders: e,
                finalUrl: c,
                status: 4 == b.readyState ? b.status: 0,
                statusText: 4 == b.readyState ? b.statusText: ""
            };
            l && 4 == b.readyState ? (b.responseType ? (e.responseXML = null, e.responseText = null, e.responseType = b.responseType) : (e.responseXML = b.responseXML, e.responseText = b.responseText), e.response = b.response) : (e.responseXML = null, e.responseText = "", e.response = null);
            return e
        },
        y = function(b) { (function(a, b) {
                for (var l = [], c = 0, d = a.length; c < d; c += b) l.push(a.slice(c, b + c));
                return l
            })(b, parseInt(a.partialSize)).forEach(function(a) {
                h("onpartial", {
                    partial: a
                })
            })
        },
        m = {
            onload: function() {
                var b = p(!0); (0 !== b.status || 200 > b.status || 300 <= b.status) && 0 < a.retries ? (a.retries--, z(a, d, g, c, h)) : function() {
                    if (a.convertBinary && b.response) {
                        var c = b.responseType ? b.responseType.toLowerCase() : "";
                        k && c !== k && console.warn("xhr: requested responseType " + k + " differs from received " + c);
                        if ("document" == c || "document" == k) if ("string" == typeof b.response) c = w(b.responseHeaders)["content-type"] || "text/html",
                        b.response = {
                            document: b.response,
                            contentType: c
                        };
                        else {
                            var c = b.response,
                            d = c.contentType || "text/html";
                            try {
                                b.response = {
                                    document: (new XMLSerializer).serializeToString(c.documentElement),
                                    contentType: d
                                }
                            } catch(f) {
                                var g = "unable to serialize content type " + d;
                                console.warn("xhr: ", g, c);
                                b.response = {
                                    error: g,
                                    contentType: d
                                }
                            }
                        } else if ("json" == c) b.response = JSON.stringify(b.response);
                        else {
                            if ("blob" == c) {
                                var h, m = new FileReader;
                                m.onload = function() {
                                    b.response = r.arrbuf2str(m.result);
                                    h()
                                };
                                m.readAsArrayBuffer(b.response);
                                return {
                                    done: function(a) {
                                        h = a
                                    }
                                }
                            }
                            "arraybuffer" == c && (b.response = r.arrbuf2str(b.response))
                        }
                    }
                    return {
                        done: function(a) {
                            a()
                        }
                    }
                } ().done(function() {
                    if (a.partialSize && d.onpartial) {
                        var e = a.convertBinary && b.response ? b.response: b.responseText; ["response", "responseText", "responseXML"].forEach(function(a) {
                            delete b[a]
                        });
                        e && (e.length > a.partialSize ? y(e) : b.response_data = e)
                    }
                    c("onload", b);
                    4 == b.readyState && c("ondone", b)
                })
            },
            onerror: function() {
                var b = p();
                4 == b.readyState && 200 != b.status && 0 != b.status && 0 < a.retries ? (a.retries--, z(a, d, g, c, h)) : (c("onerror", b), c("ondone", b))
            },
            onloadstart: function() {
                h("onloadstart",
                function() {
                    return p()
                })
            },
            onreadystatechange: function() {
                h("onreadystatechange",
                function() {
                    return p()
                })
            },
            onprogress: function(a) {
                h("onprogress",
                function() {
                    var c = p(),
                    d = c;
                    void 0 === d && (d = {});
                    try {
                        var f = null,
                        g = null;
                        if (a.lengthComputable || 0 < a.total) f = a.loaded,
                        g = a.total;
                        else {
                            var h = b.responseType && -1 == ["", "text"].indexOf(b.responseType) ? null: b.responseText,
                            k = Number(w(c.responseHeaders)["content-length"] || ""),
                            m = 2 < c.readyState && h ? h.length: 0;
                            0 == k && (k = -1);
                            f = a.loaded || m;
                            g = a.total || k
                        }
                        d.lengthComputable = a.lengthComputable;
                        d.loaded = f;
                        d.done = f;
                        d.position = f;
                        d.total = g;
                        d.totalSize = g
                    } catch(n) {}
                    return d
                })
            },
            ontimeout: function() {
                var a = p();
                c("ontimeout");
                c("ondone", a)
            },
            onabort: function() {
                var a = v("aborted");
                c("ondone", a)
            }
        },
        f = 0 == Object.keys(m).concat(["ondone"]).filter(function(a) {
            return !! d[a]
        }).length;
        if (f) throw Error("Synchronous XHR is not supported anymore");
        Object.keys(m).forEach(function(a) {
            if (d[a] || -1 != ["ontimeout", "onload", "onerror", "onabort"].indexOf(a)) b[a] = m[a]
        });
        try {
            if (!g.internal && !B(a.url)) throw Error("Invalid scheme of url: " + a.url);
            b.open(a.method || "GET", a.url, !f, a.user, a.password);
            if (a.headers || a.nocache || a.revalidate) {
                var u = {};
                a.headers && q.assign(u, a.headers);
                a.nocache ? q.assign(u, F) : a.revalidate && q.assign(u, G);
                Object.keys(u).forEach(function(a) {
                    var c = a,
                    d = u[a];
                    if (t.prefix) C(a.toLowerCase()) && (c = t.prefix + a, d = null === d ? "": r.encodeS(d));
                    else if (null === d) return;
                    try {
                        b.setRequestHeader(c, d)
                    } catch(f) {
                        console.warn("xhr: rejected header", c, u[a])
                    }
                })
            }
            void 0 !== a.overrideMimeType && b.overrideMimeType(a.overrideMimeType);
            void 0 !== a.responseType && (k = a.responseType.toLowerCase(), -1 == ["document", "json"].indexOf(k) && (b.responseType = k));
            void 0 !== a.timeout && (b.timeout = a.timeout);
            void 0 !== a.data ? ("typified" === a.data_type ? b.send(x(a.data)) : "string" === typeof a.data ? b.send(a.data) : b.send(JSON.stringify(a.data)), d.onprogress && b.upload && (b.upload.onprogress = m.onprogress)) : b.send()
        } catch(l) {
            console.error(l.stack),
            f = v(l.message),
            c("onerror", f),
            c("ondone", f)
        }
        n = n || {};
        return q.copy({
            abort: function() {
                b.abort()
            }
        },
        n)
    };
    Registry.register("xmlhttprequest", "6095",
    function() {
        return {
            run: H,
            setConfig: function(a) {
                t = a
            },
            getConfig: function() {
                return t
            },
            makeErrorResponse: v,
            parseHeaders: w
        }
    })
});